package com.ocean.binarysearch;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2023/02/03 <br>
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 7, 9};
        System.out.println(new BinarySearch().search2(nums, 5, 7));
    }

    public int search(int[] nums, int n, int value) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            // low和high在数值很大的情况 会发生溢出
//            int mid = (low + high) / 2;
            int mid = low + (high - low) / 2; // 或者是用位运算 low +(hight-low) >>1
            if (nums[mid] == value) {
                return mid;
            } else if (nums[mid] < value) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 递归实现
     *
     * @param nums
     * @param n
     * @param value
     * @return
     */
    public int search2(int[] nums, int n, int value) {
        int low = 0;
        int high = n - 1;
        return doSearch(nums, low, high, value);
    }

    private int doSearch(int[] nums, int low, int high, int value) {
        if (low > high) {
            return -1;
        }
        int mid = low + ((high - low) >> 1);
        if (nums[mid] == value) {
            return mid;
        }
        if (nums[mid] > value) {
            return doSearch(nums, low, mid - 1, value);
        }
        return doSearch(nums, mid + 1, high, value);
    }
}
